package com.cole.gx095.service.impl;

import com.cole.gx095.Repository.SaleGroupRepository;
import com.cole.gx095.service.SaleGroupService;
import com.cole.gx095.entity.SaleGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SaleGroupServiceImpl implements SaleGroupService {
    @Autowired
    SaleGroupRepository saleGroupRepository;
    @Override
    public Page<SaleGroup> findAllBy(SaleGroup saleGroup, Integer currentPage, Integer pageSize) {
        currentPage--;
        currentPage = currentPage < 0 ? 0 : currentPage;//page 为页码，数据库从0页开始
        //可以使用重载的 of(int page, int size, Sort sort) 方法指定排序字段
        Pageable pageable = PageRequest.of(currentPage, pageSize);

        Specification<SaleGroup> specification = new Specification<SaleGroup>() {
            @Override
            public Predicate toPredicate(Root<SaleGroup> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (saleGroup.getStatus()!=null&&!"".equals(saleGroup.getStatus()))
                    predicateList.add(criteriaBuilder.equal(root.get("status").as(String.class),saleGroup.getStatus()));
                if (saleGroup.getSaleperson()!=null&&!"".equals(saleGroup.getSaleperson()))
                    predicateList.add(criteriaBuilder.like(root.get("saleperson").as(String.class),"%"+saleGroup.getSaleperson()+"%"));

                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        };
        return saleGroupRepository.findAll(specification,pageable);//无数据时返回空列表;
    }
}
